<?php

namespace App\Api;


use App\Http\Controllers\Controller;
use App\Models\Admin;
use Auth;
use Illuminate\Http\Request;
use Hash;
use Illuminate\Validation\Rule;

class AdminController extends Controller
{

    public function index()
    {
        return Admin::with('roles')->get();
    }

    public function show(Admin $admin)
    {
        return $admin;
    }

    public function update(Request $request, Admin $admin)
    {
        $request->validate([
            'name' => ['required', "min:3"],
            'mobile' => ['required', Rule::unique('admins')->ignore(request()->admin), 'regex:/^1\d{10}$/i'],
        ]);

        $admin->fill($request->input())->save();
        $admin->password = Hash::make($request->password);
        return $this->message('管理员修改成功');

    }

    public function store(Request $request, Admin $admin)
    {
        $request->validate([
            'name' => ['required', "min:3"],
            'mobile' => ['required', Rule::unique('admins')->ignore(request()->admin), 'regex:/^1\d{10}$/i'],
            'password' => ['required', 'between:6,20']
        ], [
            'password.required' => '密码必须填写',
            'password.between' => '密码必须是6-20之间'
        ]);
        $admin->fill($request->input())->save();
        $admin->password = Hash::make($request->password);
        $admin->save();
        return $this->message('管理员添加成功');

    }


    public function destroy(Admin $admin)
    {
        $admin->delete();
        return $this->message('管理员删除成功');
    }

    //登录用户信息
    public function info()
    {
        return Auth::user();
    }

//    用户退出登录
    public function logout()
    {
        Auth::guard('admin')->logout();
        return $this->message('退出成功');
    }
}
